import '../models/ai_chat_message.dart';
import '../services/web_database_service.dart';

class AiChatMessageRepository {
  final WebDatabaseService _dbService = WebDatabaseService();
  static const String _tableName = WebDatabaseService.aiChatMessagesTable;

  /// 添加AI聊天消息
  Future<int> addAiChatMessage(AiChatMessage message) async {
    final data = message.toMap();
    data.remove('id'); // 移除id，让数据库自动生成
    return await _dbService.insert(_tableName, data);
  }

  /// 获取所有AI聊天消息
  Future<List<AiChatMessage>> getAllAiChatMessages() async {
    final results = await _dbService.getAll(_tableName);
    final messages = results.map((data) => AiChatMessage.fromMap(data)).toList();
    // 按创建时间排序
    messages.sort((a, b) => a.createdAt.compareTo(b.createdAt));
    return messages;
  }

  /// 根据ID获取AI聊天消息
  Future<AiChatMessage?> getAiChatMessageById(int id) async {
    final result = await _dbService.getById(_tableName, id);
    return result != null ? AiChatMessage.fromMap(result) : null;
  }

  /// 获取最近的AI聊天消息
  Future<List<AiChatMessage>> getRecentAiChatMessages(int count) async {
    final allMessages = await getAllAiChatMessages();
    // 已经按时间排序，取最后count条
    return allMessages.reversed.take(count).toList().reversed.toList();
  }

  /// 获取用户消息
  Future<List<AiChatMessage>> getUserMessages() async {
    final allMessages = await getAllAiChatMessages();
    return allMessages.where((message) => message.role == 'user').toList();
  }

  /// 获取AI助手消息
  Future<List<AiChatMessage>> getAssistantMessages() async {
    final allMessages = await getAllAiChatMessages();
    return allMessages.where((message) => message.role == 'assistant').toList();
  }

  /// 搜索聊天消息
  Future<List<AiChatMessage>> searchAiChatMessages(String keyword) async {
    final allMessages = await getAllAiChatMessages();
    return allMessages.where((message) => 
      message.content.toLowerCase().contains(keyword.toLowerCase())
    ).toList();
  }

  /// 获取指定日期范围的聊天消息
  Future<List<AiChatMessage>> getAiChatMessagesByDateRange(
    DateTime startDate,
    DateTime endDate,
  ) async {
    final allMessages = await getAllAiChatMessages();
    final startTimestamp = startDate.millisecondsSinceEpoch;
    final endTimestamp = endDate.millisecondsSinceEpoch;
    
    return allMessages.where((message) => 
      message.createdAt >= startTimestamp && message.createdAt <= endTimestamp
    ).toList();
  }

  /// 获取今日聊天消息
  Future<List<AiChatMessage>> getTodayAiChatMessages() async {
    final now = DateTime.now();
    final startOfDay = DateTime(now.year, now.month, now.day);
    final endOfDay = DateTime(now.year, now.month, now.day, 23, 59, 59);
    
    return await getAiChatMessagesByDateRange(startOfDay, endOfDay);
  }

  /// 获取聊天会话（按对话顺序）
  Future<List<AiChatMessage>> getChatSession({int? limit}) async {
    final allMessages = await getAllAiChatMessages();
    
    if (limit != null && limit > 0) {
      // 取最近的limit条消息
      return allMessages.reversed.take(limit).toList().reversed.toList();
    }
    
    return allMessages;
  }

  /// 添加用户消息
  Future<int> addUserMessage(String content) async {
    final message = AiChatMessage(
      role: 'user',
      content: content,
      createdAt: DateTime.now().millisecondsSinceEpoch,
    );
    return await addAiChatMessage(message);
  }

  /// 添加AI助手消息
  Future<int> addAssistantMessage(String content) async {
    final message = AiChatMessage(
      role: 'assistant',
      content: content,
      createdAt: DateTime.now().millisecondsSinceEpoch,
    );
    return await addAiChatMessage(message);
  }

  /// 更新AI聊天消息
  Future<void> updateAiChatMessage(AiChatMessage message) async {
    await _dbService.update(_tableName, message.toMap());
  }

  /// 删除AI聊天消息
  Future<void> deleteAiChatMessage(int id) async {
    await _dbService.delete(_tableName, id);
  }

  /// 批量添加AI聊天消息
  Future<List<int>> addAiChatMessages(List<AiChatMessage> messages) async {
    final List<int> ids = [];
    for (final message in messages) {
      final id = await addAiChatMessage(message);
      ids.add(id);
    }
    return ids;
  }

  /// 获取AI聊天消息总数
  Future<int> getAiChatMessageCount() async {
    return await _dbService.count(_tableName);
  }

  /// 获取聊天统计
  Future<Map<String, dynamic>> getChatStats() async {
    final allMessages = await getAllAiChatMessages();
    final totalMessages = allMessages.length;
    final userMessages = allMessages.where((msg) => msg.role == 'user').length;
    final assistantMessages = allMessages.where((msg) => msg.role == 'assistant').length;
    
    final totalCharacters = allMessages.fold<int>(0, (sum, msg) => sum + msg.content.length);
    final averageMessageLength = totalMessages > 0 ? (totalCharacters / totalMessages) : 0.0;
    
    return {
      'totalMessages': totalMessages,
      'userMessages': userMessages,
      'assistantMessages': assistantMessages,
      'totalCharacters': totalCharacters,
      'averageMessageLength': averageMessageLength,
    };
  }

  /// 获取今日聊天统计
  Future<Map<String, dynamic>> getTodayChatStats() async {
    final todayMessages = await getTodayAiChatMessages();
    final totalMessages = todayMessages.length;
    final userMessages = todayMessages.where((msg) => msg.role == 'user').length;
    final assistantMessages = todayMessages.where((msg) => msg.role == 'assistant').length;
    
    return {
      'totalMessages': totalMessages,
      'userMessages': userMessages,
      'assistantMessages': assistantMessages,
    };
  }

  /// 获取按日期分组的聊天消息
  Future<Map<String, List<AiChatMessage>>> getAiChatMessagesByDate() async {
    final allMessages = await getAllAiChatMessages();
    final groupedMessages = <String, List<AiChatMessage>>{};
    
    for (final message in allMessages) {
      final date = DateTime.fromMillisecondsSinceEpoch(message.createdAt);
      final dateKey = '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
      
      if (!groupedMessages.containsKey(dateKey)) {
        groupedMessages[dateKey] = [];
      }
      groupedMessages[dateKey]!.add(message);
    }
    
    return groupedMessages;
  }

  /// 清空聊天历史
  Future<void> clearChatHistory() async {
    await _dbService.clearTable(_tableName);
  }

  /// 删除指定日期之前的聊天消息
  Future<void> deleteAiChatMessagesBefore(DateTime date) async {
    final allMessages = await getAllAiChatMessages();
    final timestamp = date.millisecondsSinceEpoch;
    
    for (final message in allMessages) {
      if (message.createdAt < timestamp && message.id != null) {
        await deleteAiChatMessage(message.id!);
      }
    }
  }

  /// 导出聊天记录为文本
  Future<String> exportChatHistoryToText() async {
    final allMessages = await getAllAiChatMessages();
    final buffer = StringBuffer();
    
    String? currentDate;
    
    for (final message in allMessages) {
      final messageDate = DateTime.fromMillisecondsSinceEpoch(message.createdAt);
      final dateStr = '${messageDate.year}-${messageDate.month.toString().padLeft(2, '0')}-${messageDate.day.toString().padLeft(2, '0')}';
      
      if (currentDate != dateStr) {
        if (currentDate != null) buffer.writeln();
        buffer.writeln('=== $dateStr ===');
        currentDate = dateStr;
      }
      
      final timeStr = '${messageDate.hour.toString().padLeft(2, '0')}:${messageDate.minute.toString().padLeft(2, '0')}';
      final roleStr = message.role == 'user' ? '用户' : 'AI助手';
      
      buffer.writeln('[$timeStr] $roleStr: ${message.content}');
    }
    
    return buffer.toString();
  }
}